package com.wtg.client.control;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("oauth")
public class OauthControl {
	
	@Autowired
	private RestTemplate restTemplate;
	
	@RequestMapping("giteeCallback")
	@SuppressWarnings("unchecked")
	public String giteeCallback(String code, HttpServletRequest request) {
		//通过code去获得
		String client_id = "77e9ce8b9e727a6af8da3381b40b405af87abab4b7330c688b2ce3c084c6c7df";
		String client_secret = "effb69fe00b34398781d0f0dd01bde80a0b702c41f23d2c7a0588a46be9fec1a";
		String redirect_uri = "http://localhost:22000/clientTwo/oauth/giteeCallback";
		String url = "https://gitee.com/oauth/token?grant_type=authorization_code"
				+ "&code="+code
				+"&client_id="+client_id
				+"&client_secret="+client_secret
				+"&redirect_uri="+redirect_uri;
		//{access_token=3a648061d2648907c47aeed6ddcf9a51, token_type=bearer, expires_in=86400, refresh_token=428b50abb94d8c629261271aca3fde0bf475371d631e7fd54d96ae2e229b34e8, scope=user_info, created_at=1617262283}
		Map<String,String> map = restTemplate.postForEntity(url, null, Map.class).getBody();
		String access_token = map.get("access_token");
		//获得用户信息
		url = "https://gitee.com/api/v5/user?access_token="+access_token;
		map = restTemplate.getForEntity(url, Map.class).getBody();
		//将access_token放入缓存
		//访问的登录接口，内部实现为根据gitee的access_token查询出本地账号并进行登录操作
		return access_token;
	}

}
